#include "batch.h"
#include "db.h"
#include "global.h"
#include "operation.h"
#include "u.h"
#include "user.h"
#include <qdatetime.h>
#include <qdebug.h>

Batch::Batch(QObject *parent)
    : QAbstractListModel(parent)
{
    qDebug() << __FUNCTION__ << __LINE__;
    // 可以立即加载初始数据
    DB* db = DB::getInstance();
    m_roles = db->getTableFieldRole("batch");
    loadBatch("");
}

bool Batch::addBatch(QString product, QString workShop)
{
    qDebug() << __FUNCTION__ << __LINE__;
    User* pUser = (User*)Global::instance().get("userInfo");
    QString loginName = pUser->currentLogin()["name"].toString();
    QString realName = pUser->currentLogin()["real_name"].toString();
    // DB::getInstance()->addUser(name, password, real_name, expiration, status, permission, create_by);
    DB::getInstance()->addBatch(loginName, realName, m_batchNo, product, workShop, U::getDateTimeSTD(), loginName);
    m_product = product;
    m_workShop = workShop;
    loadBatch("");
    Operation* pOperation =  (Operation*)Global::instance().get("operationInfo");
    pOperation->insertOperationLog("批次启动",QString("批号[%1],产品[%2],车间[%3]").arg(m_batchNo).arg(product).arg(workShop), "");
    return true;
}

bool Batch::updateBatch(QString desc)
{
    qDebug() << __FUNCTION__ << __LINE__;
    DB::getInstance()->updateBatch(desc, U::getDateTimeSTD(), m_batchNo, m_product, m_workShop);
    Operation* pOperation =  (Operation*)Global::instance().get("operationInfo");
    pOperation->insertOperationLog("批次停止",QString("描述[%1]").arg(desc), "");

    loadBatch("");
    return true;

}

QVariantMap Batch::get(int row) const
{
    qDebug() << __FUNCTION__ << __LINE__;
    QVariantMap result;
    if (row < 0 || row >= m_records.size())
        return result;
    const QHash<QString,QVariant> &record = m_records[row];
    for (auto it = record.begin(); it != record.end(); ++it) {
        result[it.key()] = it.value();
    }
    return result;
}

int Batch::rowCount(const QModelIndex &parent) const
{
    // qDebug() << __FUNCTION__ << __LINE__;
    return m_records.size();
}

QVariant Batch::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_records.size())
        return QVariant();

    //qDebug() << __FUNCTION__ << __LINE__ << "role:" << role << "-index:" << index.row();
    const QHash<QString, QVariant> has = m_records[index.row()];

    return has[m_roles[role]];
}

QHash<int, QByteArray> Batch::roleNames() const
{
    qDebug() << __FUNCTION__ << __LINE__ ;
    return m_roles;
}

QString Batch::batchNo()
{
    qDebug() << "batchNo" << m_batchNo;
    return m_batchNo;
}

void Batch::setBatchNo(QString batchNo)
{
    qDebug() << "setBatchNo" << batchNo;
    this->m_batchNo = batchNo;
}


bool Batch::loadBatch(const QString& filter)
{
    qDebug() << __FUNCTION__ << __LINE__;
    DB* db = DB::getInstance();
    beginResetModel();
    m_records = db->queryBatches(filter);
    endResetModel();
    return true;
}
